// 引入SDK核心类
var QQMapWX = require('../../../libs/qqmap-wx-jssdk.js');
var _key = "AFBBZ-26436-QYCSL-ESUEC-SGGWJ-KEBAS";
var qqmapsdk;
const app = getApp();
Page({
  data:{
   
  },
  // 拖动地图触发事件
  regionChange:function(e){
    console.log(e)
    var that = this;
	console.log(e.type);
    // 改变中心点位置  
    if (e.type == "end") {
      getCenterLocation(that);
    };
  },
  backadress:function(e){
    var that = this;
    var pages = getCurrentPages(); // 获取页面栈
    var currPage = pages[pages.length - 1]; // 当前页面
    var prevPage = pages[pages.length - 2]; // 上一个页面
	console.log(that);
    prevPage.setData({
      userRess: {
        province: that.data.province,
        city: that.data.city,
        area: that.data.area,
		  addressInfo: that.data.addressInfo + this.data.posiAddress[0].title,
        longitude: that.data.longitude,
        latitude: that.data.latitude
       },
      isnewedit:1,
		please:0
    });
    wx.navigateBack({
      delta: 1
    })
  },
  clickposi:function(e){
    var that = this;
    var pages = getCurrentPages(); // 获取页面栈
    var currPage = pages[pages.length - 1]; // 当前页面
    var prevPage = pages[pages.length - 2]; // 上一个页面
    prevPage.setData({
      userRess: {
        province: that.data.province,
        city: that.data.city,
        area: that.data.area,
        addressInfo:that.data.addressInfo + e.currentTarget.dataset.text,
        longitude: e.currentTarget.dataset.longitude,
        latitude: e.currentTarget.dataset.latitude
      },
      isnewedit: 1,
		please:0
    });
    wx.navigateBack({
      delta: 1
    })
  },
	onLoad: function (options) {
    var that = this;
    console.log(options);
     // 已经进行地理位置授权
        if (options.latitude&&options.longitude) {
           that.setData({
              isman: 1,
              options:{
                latitude: options.latitude,
                longitude: options.longitude
              }
            });
          };
		qqmapsdk = new QQMapWX({
			key: _key
		});
    console.log(that.data.posiAddress);
	},
	onShow: function () {
    var that = this;
    console.log(that.data)
    wx.getSetting({
      success: function (data) {
        // console.log(data)
        if (data.authSetting['scope.userLocation'] == true) {
          if (that.data.isman == 1 && that.data.options.latitude && that.data.options.longitude) {
            console.log(1);
            // 获取当前用户的经纬度
            // wx.getLocation({
            //   type: "gcj02",  //修改编码格式,微信默认编码格式有偏差
            //   altitude: true,
            //   success: function (res) {
            //     console.log(res);
                that.setData({
                  latitude: that.data.options.latitude,
                  longitude: that.data.options.longitude
                });
                getLoal(that.data.options.latitude, that.data.options.longitude, that);
            //   },
            //   fail: function (res) {
            //     console.log(res);
            //   },
            // });
          } else {
            // 获取当前用户的经纬度
            console.log(2)
				var loc = wx.getStorageSync('location');
				console.log(loc);
				that.setData({
					latitude: loc.lat,
					longitude: loc.lng
				});
			  getLoal(loc.lat, loc.lng, that);
            // wx.getLocation({
            //   type: "gcj02",  //修改编码格式,微信默认编码格式有偏差
            //   success: function (res) {
            //     console.log(res);
            //     that.setData({
            //       latitude: res.latitude,
            //       longitude: res.longitude
            //     });
            //     getLoal(res.latitude, res.longitude, that);
            //   },
            //   fail: function (res) {
            //     console.log(res);
            //   },
            // });
          }
        } else {
          // 弹出地理位置授权窗口
          // 开始授权
          wx.showModal({
            title: '提示',
            content: '"城跑"需要获取你的地理位置',
            success(a) {
              if (a.confirm) {
                console.log('用户点击确定');
                wx.openSetting({
                  scope: "scope.userLocation",
                  success() {
                    // 获取当前用户的经纬度
                    console.log(2);
                    wx.getLocation({
                      type: "gcj02",  //修改编码格式,微信默认编码格式有偏差
                      altitude: true,
                      success: function (res) {
                        console.log(res);
                        that.setData({
                          latitude: res.latitude,
                          longitude: res.longitude
                        });
                        getLoal(res.latitude, res.longitude, that);
                      },
                      fail: function (res) {
                        console.log(res);
                      },
                    });
                  },
                  fail: function (res) {
                    console.log(res);
                    console.log(3);
                  },
                })
              } else if (a.cancel) {
                // 返回上级页面
                wx.navigateBack({
                  delta: 1
                });
              }
            }
          });
        }
      },
      fail: function (data) {
      }
    });
		// 调用接口
		qqmapsdk.search({
      // keyword: ['住宅', '火车站'],  //搜索关键词
      keyword: '全部',
			success: function (res) {
				console.log(res);
			},
			fail: function (res) {
				console.log(res);
			},
			complete: function (res) {
				console.log(res);
			}
		});
	},
});
function getLoal(lat, lon,that) {
  qqmapsdk.reverseGeocoder({
    location: {
      latitude: lat,
      longitude: lon
    },
    success: function (res) {
      console.log(res)
      that.setData({
        province: res.result.address_component.province,
        city: res.result.address_component.city,
        area: res.result.address_component.district,
        addressInfo: res.result.address_component.street,
        longitude: res.result.location.lng,
        latitude: res.result.location.lat
      });
      getAddressList(lat, lon, function (res) {
        that.setData({
          posiAddress: res
        });
      })
    },
    fail: function (res) {
    }
  })
};
var dis = 0;
function getCenterLocation(that){

var mapCtx = wx.createMapContext("qqMap");
  mapCtx.getCenterLocation({
    success: function (res) {
		var distance = getDistance(res.latitude, res.longitude, that.data.lat, that.data.log)
		console.log(distance)
		console.log(dis)
		if(dis != distance){
			dis = distance;
      		getLoal(res.latitude, res.longitude, that);
			return;
		}else{
			return;
		}
		
		// if ((res.latitude == that.data.lat && res.longitude == that.data.log) || distance < 2) {
		// 	return;
		// }
    }
  });
}
function getAddressList(lat, lng, _fun) {
  // 事件触发，调用接口
  var _this = this;
  // 调用接口
  qqmapsdk.search({
    // keyword: ['住宅','火车站'],  //搜索关键词
    keyword: '全部',
    location: [lat, lng].join(","),  //设置周边搜索中心点
    success: function (res) { //搜索成功后的回调
      var mks = []
      for (var i = 0; i < res.data.length; i++) {
        mks.push({ // 获取返回结果，放到mks数组中
          title: res.data[i].title,
          id: res.data[i].id,
          latitude: res.data[i].location.lat,
          longitude: res.data[i].location.lng,
        })
      }
      //_this.setData({ //设置markers属性，将搜索结果显示在地图中
      return typeof _fun == "function" && _fun(mks)
      //})
    },
    fail: function (res) {
      console.log(res);
    },
    complete: function (res) {
      console.log(res);
    }
  });
}
function getDistance(lat1, lng1, lat2, lng2) {

	lat1 = lat1 || 0;

	lng1 = lng1 || 0;

	lat2 = lat2 || 0;

	lng2 = lng2 || 0;

	var rad1 = lat1 * Math.PI / 180.0;

	var rad2 = lat2 * Math.PI / 180.0;

	var a = rad1 - rad2;

	var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;

	var r = 6378137;

	return (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))).toFixed(0)
}